package com.jn.glide.presenter;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.jn.glide.common.WeakRrfHandler;
import com.jn.glide.contract.EatQQContract;
import com.jn.glide.entity.EatQQEntity;
import com.jn.glide.http.GlobalRetrofitClient;
import com.jn.glide.service.EatQQService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class EatQQPresenter implements EatQQContract.IEatQQPresenter {
    public static final int HTTP_SUCCESS = 0;
    public static final int HTTP_FAIL = 1;
    private EatQQContract.IEatQQView mView;

    public EatQQPresenter(EatQQContract.IEatQQView view) {
        mView = view;
    }

    @Override
    public void getData(String qq) {
        mView.onHttpLoading(true);
        EatQQService service = GlobalRetrofitClient.getInstance().create(EatQQService.class);
        service.getData(qq).enqueue(new Callback<EatQQEntity>() {
            @Override
            public void onResponse(Call<EatQQEntity> call, Response<EatQQEntity> response) {
                Message message = Message.obtain();
                message.obj = response.body();
                message.what = HTTP_SUCCESS;
                mHandler.sendMessage(message);
            }

            @Override
            public void onFailure(Call<EatQQEntity> call, Throwable t) {

            }
        });
    }

    WeakRrfHandler<EatQQPresenter> mHandler = new WeakRrfHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int result = msg.what;
            switch (result) {
                case HTTP_SUCCESS:
                    EatQQEntity entity = (EatQQEntity) msg.obj;
                    if (mView != null) {
                        mView.onHttpLoading(false);
                        mView.showData(entity);
                    }
                    break;
                case HTTP_FAIL:
                    break;
            }
            return false;
        }
    });
}